var Dispatcher = function(){
  this.cb = null;
}
Dispatcher.prototype.register = function(cb){
  this.cb = cb;
}
Dispatcher.prototype.dispatch = function(payload){
  this.cb(payload);
}

var Store = {
  list: [],
  cb: null,
  getList: function(){
    return this.list;
  },
  addNewItem : function(item) {
    this.list.push(item);
    this.cb();
  },
  addChangeListern(cb){
    this.cb = cb;
  }
}

// let AppDispatcher = new Flux.Dispatcher();
let AppDispatcher = new Dispatcher();

AppDispatcher.register(function (action) {
  console.log(action);
  switch(action.actionType) {
    case 'ADD_NEW_ITEM':
      console.log('ADD_NEW_ITEM');
      Store.addNewItem(action.text);
      break;
    default:
      console.log('default');
      // no op
  }
})

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      list: Store.getList()
    }
  }
  componentDidMount() {
    Store.addChangeListern(this._onChange.bind(this));
  } 
  componentWillUnmount() {
  }
  handleClick(){
    AppDispatcher.dispatch({
      actionType:'ADD_NEW_ITEM',
      text: 'text'
    })
  }
  _onChange(){
    this.setState({
      list: Store.getList()
    });
  }
  render() {
    let list = this.state.list;
    return (
      <div>
        <h1>flux demo</h1>
        <button onClick={this.handleClick.bind(this)}>click me</button>
        <ol>
         {
            list.map( (item,index) => {
              return <li key={index}>item</li>;
            })
         }
        </ol>
      </div>
    );
  }
}
ReactDOM.render(
  <App />,
  document.getElementById('root')
);